import Vue from 'vue'
// import router from '@/router'
import store from '@/store'
import { getChat } from '@/api/system'
import { mobileReg } from './tools/validate'
import { uploadPic } from '@/api/common'
import CONSTANT from '@/constant/index'
import util from '@/utils/util'
const Base64 = require('js-base64').Base64

// 判断是mobile 还是pc
export function isMobile() {
	// 移动端
	if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
		return true
	}
	return false
}
// 获取当前连接地址
export function getUrlHref() {
	// let comProtocolUrl = window.location.protocol // 协议
	// let comHostUrl = window.location.host // 主机
	// let url = comProtocolUrl + '//' + comHostUrl
	// url = 'http://dev.meijiabang.com'
	return CONSTANT.formal
}

/** *
 * 跳转到商城
 * @parmas jumpUrl 跳转的页面地址
 * @parmas attrUrl 用户的头像地址
 * @parmas titleName 用户的名字
 * @parmas urlEndStr 跳转的页面url需要补充的参数 例'&aaa=111'
 */
export function jumpShop(jumpUrl, attrUrl, titleName, urlEndStr) {
	const basicUserInfo = store.state.user.basicUser
	const adminUserInfo = store.state.user.user
	const userInfo = basicUserInfo || adminUserInfo
	let name = titleName || userInfo.nick_name + '的家居商城'
	// let name = titleName || document.title + '的家居商城'
	name = encodeURI(name)
	attrUrl = attrUrl ? encodeURI(attrUrl) : ''

	// let hostUrl = 'http://192.168.0.124:8081'
	// let hostUrl = 'https://mall.meijiabang.com'
	const hostUrl = CONSTANT.formal

	let isSelf = ''
	if (CONSTANT.oemSource == 3) {
		isSelf = ''
	} else {
		isSelf = userInfo.user_id == uni.getStorageSync('user_id')
	}

	const utlToken = isSelf ? `&token=${uni.getStorageSync('token')}&type=hkds_miniapp` : ''

	const idStr = `?owner_user_id=${userInfo.user_id}&parent_id=${userInfo.user_id}&isSelf=${isSelf}${utlToken}${urlEndStr || ''}`

	const url = `${hostUrl}/mobile/#${jumpUrl}${idStr}&hkds_name=${name}&hkds_attr=${attrUrl}`

	// 获取小程序地址完整路径
	let getRoute = getMiniAppUrl()
	const allUrl = url + '&returnUrl=' + getRoute
	// location.href = allUrl

	console.log(`/pages/page/webview/index?returnUrl=${encodeURIComponent(allUrl)}`)
	uni.navigateTo({
		url: `/pages/page/webview/index?returnUrl=${encodeURIComponent(allUrl)}`
	})
}

// 获取小程序地址完整路径
export function getMiniAppUrl() {
	let getCurPages = getCurrentPages()
	if (getCurPages.length == 0) return false
	let getCurPagesObj = getCurPages[getCurPages.length - 1]
	let getRoute = getCurPagesObj.route + queryData(getCurPagesObj.options)

	return getRoute
}

// 获取c端首页路径
export function getSpreadIndex() {
	const userInfo = store.state.user.basicUser ? store.state.user.basicUser : store.state.user.user
	let text = ''
	switch (userInfo.role_id) {
		case 1:
			text = `/pages/design/designCompany/indexNew`
			break
		case 2:
			text = `/pages/design/material/index`
			break
		case 3:
			text = `/pages/design/designerIndex`
			break
		default:
			text = '/pages/design/designCompany/indexNew'
			break
	}
	return text
}

// 跳转到别人的主页
export function jumpOtherUser(owner_user_id, role_id) {
	switch (role_id) {
		case 1:
			uni.navigateTo({
				url: `/pages/design/designCompany/indexNew?owner_user_id=${owner_user_id}`
			})
			break
		case 2:
			uni.navigateTo({
				url: `/pages/design/material/index?owner_user_id=${owner_user_id}`
			})
			break
		case 3:
			uni.navigateTo({
				url: `/pages/design/designerIndex?owner_user_id=${owner_user_id}`
			})
			break
		default:
			uni.navigateTo({
				url: `/pages/design/designerIndex?owner_user_id=${owner_user_id}`
			})
			break
	}
}

// 获取当前时间戳
export function getTimestamp() {
	return Date.parse(new Date())
}
// 生成从minNum到maxNum的随机数
export function getRandomNum(minNum, maxNum) {
	switch (arguments.length) {
		case 1:
			return parseInt(Math.random() * minNum + 1, 10)
			// eslint-disable-next-line no-unreachable
			break
		case 2:
			return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10)
			break
		default:
			return 0
			break
	}
}

// 防抖
export function debounce(fn, time) {
	let handle
	return function(fn, time) {
		// 取消之前的延时调用
		clearTimeout(handle)
		handle = setTimeout(() => {
			fn.call(this)
		}, time || 50)
	}
}
// 节流(规定的时间才触发)
export function throttle(func, delay) {
	var prev = Date.now()
	return function(func, delay) {
		var context = this
		var args = arguments
		var now = Date.now()
		if (now - prev >= delay) {
			func.apply(context, args)
			prev = Date.now()
		}
	}
}
// 登录页面公共地址栏参数传递

export function loginParmas(data) {
	// eslint-disable-next-line one-var
	const query = {},
		ownerUserId = data.owner_user_id,
		shareUserId = data.share_user_id,
		pShareUserId = data.p_share_user_id,
		recommendAdminId = data.recommend_admin_id,
		f = data.f
	// eslint-disable-next-line camelcase
	if (ownerUserId) {
		query['owner_user_id'] = ownerUserId
	}
	if (shareUserId) {
		query['share_user_id'] = shareUserId
	}
	if (pShareUserId) {
		query['p_share_user_id'] = pShareUserId
	}
	if (recommendAdminId) {
		query['recommend_admin_id'] = recommendAdminId
	}
	if (f) {
		query['f'] = f
	}

	return query
}

/** *
 * 根据时间戳获取日期时间
 * fmt格式 例：yyyy-MM-dd hh:mm:ss
 * status 为 true 时是13位时间
 */
export function getFormatDate(time, fmt, status) {
	try {
		time = status ? time : time * 1000
		const now = new Date(time)
		return now.Format(fmt)
	} catch (e) {
		if (window.console) {
			console.log(e)
		}
	}
}
/** *
 * 时间格式化
 */
// eslint-disable-next-line no-extend-native
Date.prototype.Format = function(fmt = 'yyyy-MM-dd hh:mm:ss') {
	const o = {
		'M+': this.getMonth() + 1, // 月份
		'd+': this.getDate(), // 日
		'h+': this.getHours(), // 小时
		'm+': this.getMinutes(), // 分
		's+': this.getSeconds(), // 秒
		'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
		S: this.getMilliseconds() // 毫秒
	}
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(
			RegExp.$1,
			(this.getFullYear() + '').substr(4 - RegExp.$1.length)
		)
	}
	for (const k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
		}
	}
	return fmt
}

/** *
 * 根据日期获取时间戳
 * @parmas yyyy-MM-dd hh:mm:ss
 */
// 获取时间戳方法
export function getDataTimestamp(time) {
	let etime = time
	etime = new Date(etime)
	etime = etime.getTime()
	return etime
}

// 判断是否为用户角色类型（个人: true || 企业: false）
export function isPersonRoleType(roleType) {
	// 装修公司或材料商
	if (roleType === 1 || roleType === 2) {
		return false
	}
	// 其余类型均属于个人
	return true
}

/** *
 * 是否是微信浏览器
 */
export function isWxBrowser() {
	const ua = window.navigator.userAgent.toLowerCase()
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true
	} else {
		return false
	}
}

/** *
 * 是否是微信小程序
 */
export async function isWxMiniapp() {
	let status = false
	const ua = navigator.userAgent.toLowerCase()
	// ios的ua中无miniProgram，但都有MicroMessenger（表示是微信浏览器）
	// eslint-disable-next-line
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		await wx.miniProgram.getEnv(function(res) {
			if (res.miniprogram) {
				status = true
			} else {
				// 走不在小程序的逻辑
				status = false
			}
		})
	} else {
		// 走不在小程序的逻辑
		status = false
	}
	return status
}

// 判断是用户角色类型
export function getRoleTypeText(roleType) {
	if (roleType === 0) {
		return '普通用户'
	}
	// 装修公司或材料商
	if (roleType === 1) {
		return '装修公司'
	}
	if (roleType === 2) {
		return '经销商'
	}
	if (roleType === 3) {
		return '设计师'
	}
	if (roleType === 4) {
		return '店长/导购'
	}
	if (roleType === 5) {
		return '安装工'
	}
	if (roleType === 6) {
		return '家居顾问'
	}
}

// 判断是用户角色类型
export function getRoleTypeId(roleTypeText) {
	if (roleTypeText === '普通用户') {
		return 0
	}
	// 装修公司或材料商
	if (roleTypeText === '装修公司') {
		return 1
	}
	if (roleTypeText === '材料商') {
		return 2
	}
	if (roleTypeText === '设计师') {
		return 3
	}
	if (roleTypeText === '店长/导购') {
		return 4
	}
	if (roleTypeText === '安装工') {
		return 5
	}
	if (roleTypeText === '家居顾问') {
		return 6
	}
}
// 验证手机号码格式
export function verifiPhone(phone) {
	if (phone.length != 11) {
		return false
	}
	return mobileReg.test(phone)
}

/** *
 * 获取位置距离
 * data 经纬度数据信息
 */
export function calcDistance(data) {
	let userRegions = uni.getStorageSync('userRegion')
	if (!userRegions || !data) {
		return
	}
	userRegions = JSON.parse(userRegions)
	if (userRegions && data.lat && data.lng) {
		// eslint-disable-next-line one-var
		const lat1 = data.lat * 1,
			lng1 = data.lng * 1,
			lat2 = parseFloat(userRegions.postion.lat),
			lng2 = parseFloat(userRegions.postion.lng)

		return parseInt(calcDistanceFn(lat1, lng1, lat2, lng2))
	}
}
// 计算距离 公用方法
export function calcDistanceFn(lat1, lng1, lat2, lng2) {
	const f = (((lat1 + lat2) / 2) * Math.PI) / 180.0
	const g = (((lat1 - lat2) / 2) * Math.PI) / 180.0
	const l = (((lng1 - lng2) / 2) * Math.PI) / 180.0

	let sg = Math.sin(g)
	let sl = Math.sin(l)
	let sf = Math.sin(f)

	let s, c, w, r, d, h1, h2
	const a = 6378.137 // 取WGS84标准参考椭球中的地球长半径 单位M
	const fl = 1 / 298.257

	sg = sg * sg
	sl = sl * sl
	sf = sf * sf

	s = sg * (1 - sl) + (1 - sf) * sl
	c = (1 - sg) * (1 - sl) + sf * sl

	w = Math.atan(Math.sqrt(s / c))
	r = Math.sqrt(s * c) / w
	d = 2 * w * a
	h1 = (3 * r - 1) / 2 / c
	h2 = (3 * r + 1) / 2 / s

	return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg))
}

// 区
// 去联系客服
export function jumpToChat() {
	const basicUserInfo = store.state.user.basicUser
	const adminUserInfo = store.state.user.user
	const userInfo = basicUserInfo || adminUserInfo
	const token = uni.getStorageSync('token')
	if (!token) {
		// c端未登录的用户访问
		let target_url = `/api/v4/chat?goods_id=0&shop_id=${userInfo.user_id}&redirect=1`
		let returnUrl = CONSTANT.formal + `/apihkds/api/oauth/code?type=wechat&loginJump=1&addToken=1&target_url=${Base64.encode(target_url)}`
		uni.navigateTo({
			url: `/pages/page/webview/index?user_id=${userInfo.user_id}&returnUrl=${encodeURIComponent(returnUrl)}`
		})
		return false
	}
	const data = {
		goods_id: 0,
		shop_id: userInfo.user_id
	}
	getChat(data).then(res => {
		if (res.status == 'success') {
			// window.location.href = res.data.url
			uni.navigateTo({
				url: `/pages/page/webview/index?user_id=${userInfo.user_id}&returnUrl=${encodeURIComponent(res.data.url)}`
			})
		} else {
			uni.showToast({
				title: '您当前未登录，正在跳转登陆页面！',
				duration: 1000,
				complete: () => {
					uni.navigateTo({
						url: '/pages/page/login/index'
					})
				}
			})
		}
	})
}
export function queryData(data, getArr) {
	let queryStr = ''
	let num = 0
	for (const i in data) {
		if (!util.isEmpty(data[i])) {
			if (num === 0) {
				let arr = data[i]
				if (getArr && Array.isArray(arr)) {
					let str = ''
					for (let j = 0; j < arr.length; j++) {
						if (j == 0) {
							str += `${i}[${j}]=${arr[j]}`
						} else {
							str += `&${i}[${j}]=${arr[j]}`
						}
					}
					queryStr += `?${str}`
				} else {
					queryStr += `?${i}=${data[i]}`
				}
			} else {
				let arr = data[i]
				if (getArr && Array.isArray(arr)) {
					let str = ''
					for (let j = 0; j < arr.length; j++) {
						str += `&${i}[${j}]=${arr[j]}`
					}
					queryStr += `${str}`
				} else {
					queryStr += `&${i}=${data[i]}`
				}
			}
			num++
		}
	}
	return queryStr
}

// 上传图片到服务器
export function upLoadImg(arr) {
	let params = {}
	if (arr.length === 1) {
		params['file[content]'] = arr[0]
	} else {
		arr.forEach((item, index) => {
			params[`file[${index}][content]`] = item
		})
	}
	return new Promise((resolve, reject) => {
		if (arr.length) {
			uploadPic({
				...params,
				relative_path: 1
			}).then(res => {
				if (res.status === 'success') {
					const list = res.data.image_url.reverse()
					resolve(list)
				} else {
					reject(res)
				}
			})
		} else {
			resolve(arr)
		}
	})
}
// weixin 64转图片
export function weixinBase64src(base64data) {
	return new Promise((resolve, reject) => {
		const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []
		if (!format) {
			return (new Error('ERROR_BASE64SRC_PARSE'))
		}
		const filePath = `${wx.env.USER_DATA_PATH}/temporary_files1111aaccdd996633acv.${format}`
		const buffer = wx.base64ToArrayBuffer(bodyData)
		uni.getFileSystemManager().writeFile({
			filePath,
			data: buffer,
			encoding: 'binary',
			success: function(res) {
				resolve(filePath)
			},
			fail: function(err) {
				reject()
				console.log(err)
			}
		})
	})
}

export function deepCopy(obj) {
	if (typeof obj !== 'object') { return }
	var str = JSON.stringify(obj)
	return JSON.parse(str)
}

// 复制到粘贴板
export function copyText(str) {
	let that = this
	// #ifdef H5
	// 动态创建 textarea 标签
	const textarea = document.createElement('textarea')
	// 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘，同时将 textarea 移出可视区域
	textarea.readOnly = 'readonly'
	textarea.style.position = 'absolute'
	textarea.style.left = '-9999px'
	// 将要 copy 的值赋给 textarea 标签的 value 属性
	textarea.value = str
	// 将 textarea 插入到 body 中
	document.body.appendChild(textarea)
	// 选中值并复制
	textarea.select()
	textarea.setSelectionRange(0, textarea.value.length)
	const result = document.execCommand('Copy')
	if (result) {
		that.$toast('复制成功')
	}
	document.body.removeChild(textarea)
	// #endif

	// #ifndef H5

	uni.setClipboardData({
		data: str,
		success: function() {
			that.$toast('复制成功')
		}
	})
	// #endif
}
export default {
	copyText,
	deepCopy,
	debounce,
	throttle,
	getUrlHref,
	jumpShop,
	getMiniAppUrl,
	getTimestamp,
	getRandomNum,
	loginParmas,
	getFormatDate,
	isMobile,
	getDataTimestamp,
	jumpOtherUser,
	isPersonRoleType,
	isWxBrowser,
	isWxMiniapp,
	getRoleTypeText,
	getRoleTypeId,
	verifiPhone,
	calcDistance,
	jumpToChat,
	queryData,
	upLoadImg,
	getSpreadIndex
}
